package com.javaAdmin.server;


import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javaAdmin.mapper.AdminMapper;
import com.javaAdmin.mapper.AdminRoleMapper;
import com.javaAdmin.model.Admin;
import com.javaAdmin.model.AdminRole;
import com.javaAdmin.model.PageParam;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author Administrator
 */
@Service
public class AdminServer extends ServiceImpl<AdminMapper, Admin> {

    /**
     * 使用mb-plus后 就不用在引入下面的的，上面extends就已经引入了
     */
    //@Resource
    //private AdminMapper adminMapper;

    @Resource
    private AdminRoleMapper adminRoleMapper;

    /**
     * 新增管理员
     * 注意使用 @DS   Transactional需要加 rollbackFor = Exception.class
     * @param name
     * @param password
     * @param roleId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @DS("master")
    public Admin save(String name, String password, int roleId) {
        //加管理员
        Admin admin = new Admin();
        admin.setName(name);
        admin.setPassword(password);
        admin.setAddress("asd");
        admin.setCreateDate(new Date());
        admin.setUpdateDate(new Date());
        baseMapper.insert(admin);
        //adminMapper.insert(admin);

        //新增规则
        AdminRole adminRole = new AdminRole();
        int id = admin.getId();
        adminRole.setAdminId(id);
        adminRole.setRoleId(roleId);
        adminRoleMapper.save(adminRole);
        return admin;

    }

    public Admin deleteById(String id) {
        baseMapper.deleteById(id);
        //adminMapper.deleteById(id);
        return null;
    }

    public Page<Admin> listPage(PageParam pageParam, Admin admin) {
        // Page page = new Page<Admin>(pageParam.getPageNumber(), pageParam.getPageSize());
        // return baseMapper.selectPage(page, new QueryWrapper<>());

        Page page = new Page<Admin>(pageParam.getPageNumber(), pageParam.getPageSize());
        return baseMapper.listPage(page, admin);
    }
}
